package net.skystudio.es.service.impl;

import net.skystudio.es.elastic.repository.OperateLogRepository;
import net.skystudio.es.entity.OperateLog;
import net.skystudio.es.service.OperateLogService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OperateLogServiceImpl implements OperateLogService {

    @Autowired
    private OperateLogRepository operateLogRepository;

    @Override
    public long count() {
        return operateLogRepository.count();
    }

    @Override
    public OperateLog save(OperateLog operateLog) {
        return operateLogRepository.save(operateLog);
    }

    @Override
    public void delete(OperateLog operateLog) {
        operateLogRepository.delete(operateLog);
    }

    @Override
    public Iterable<OperateLog> getAll() {
        return operateLogRepository.findAll();
    }

    @Override
    public List<OperateLog> getBySystemName(String systemName) {
        List<OperateLog> result = new ArrayList<>();
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("systemName", systemName);
        Iterable<OperateLog> iterable  = operateLogRepository.search(matchQueryBuilder);
        iterable.forEach(e -> result.add(e));
        return result;
    }

    @Override
    public Page<OperateLog> pageQuery(Integer pageNo, Integer pageSize, String systemName) {
        NativeSearchQuery searchQuery =  new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchPhraseQuery("systemName", systemName))
                .withPageable(PageRequest.of(pageNo, pageSize))
                .build();
        return operateLogRepository.search(searchQuery);
    }
}
